package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.RadeData;
import com.xmy.cultivate.entity.views.IntegralStatisticsRs;
import com.xmy.cultivate.respons.RadeDataRs;
import com.xmy.cultivate.service.IMqPushService;
import com.xmy.cultivate.service.IRadeDataService;
import com.xmy.cultivate.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 各项率数据 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-04-29
 */
@RestController
@RequestMapping("/api/radeData")
public class RadeDataController extends BaseController {

    @Autowired
    IRadeDataService iRadeDataService;

    @Autowired
    IMqPushService iMqPushService;

    /**
     * 业绩数据
     *
     * @param pageNum        偏移位置
     * @param pageSize       偏移量
     * @param export         是否导出，0否1是
     * @param yearPart       年份
     * @param quarterNum     学期
     * @param schoolId       校区id
     * @param teacherName    老师姓名
     * @param startLessonNum 开始课次
     * @param endLessonNum   结束课次
     * @param subjectsId     科目
     * @param yearClassId    年级
     * @param fiducialSetId  项目id
     * @param departmentId   部门id
     * @param examNum        考试名称
     * @param type           类型，1教师，2年级负责人，3主管
     * @param dataModule     分类模块，1个人数据，2管理数据
     */
    @GetMapping("/getRateByTeacherList")
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "-1", required = false) Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "-1", required = false) Integer pageSize,
                          @RequestParam(value = "export", defaultValue = "0", required = false) Integer export,// 是否导出，0否1是
                          @RequestParam(value = "yearPart", required = false) Integer yearPart,
                          @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                          @RequestParam(value = "schoolId", required = false) String schoolId,
                          @RequestParam(value = "teacherName", required = false) String teacherName,
                          @RequestParam(value = "startLessonNum", required = false) Integer startLessonNum,
                          @RequestParam(value = "endLessonNum", required = false) Integer endLessonNum,
                          @RequestParam(value = "startYearClassId", defaultValue = "0", required = false) Integer startYearClassId,
                          @RequestParam(value = "endYearClassId", defaultValue = "9", required = false) Integer endYearClassId,
                          @RequestParam(value = "subjectsId", required = false) String subjectsId,
                          @RequestParam(value = "yearClassId", required = false) String yearClassId,
                          @RequestParam(value = "fiducialSetId", required = false) String fiducialSetId,
                          @RequestParam(value = "departmentId", required = false) String departmentId,
                          @RequestParam(value = "examNum", required = false) String examNum,
                          @RequestParam(value = "type", defaultValue = "0", required = false) Integer type,// 类型，1教师，2年级负责人，3主管
                          @RequestParam(value = "dataModule", defaultValue = "0", required = false) Integer dataModule // 分类模块，1个人数据，2管理数据
    ) throws IOException {

        IPage<RadeDataRs> iPage = new Page<>(pageNum, pageSize);

        List<Integer> lessonNumList = new ArrayList<>();
        for (Integer i = startLessonNum; i <= endLessonNum; i++) {
            lessonNumList.add(i);
        }

        Integer dataType = 1;// 1按照课次显示，2按照年级显示
        if (fiducialSetId.equals("14") || fiducialSetId.equals("15")) {
            dataType = 2;
        }

        if (dataModule == 1) {
            if (type == 1) {
                iRadeDataService.getRateByTeacherList(iPage, yearPart, quarterNum, schoolId, teacherName, fiducialSetId, subjectsId, yearClassId, lessonNumList, startLessonNum, endLessonNum, export, examNum, dataType);
            } else if (type == 2) {
                iRadeDataService.getRateByYearClassTeacherOwnList(iPage, yearPart, quarterNum, schoolId, teacherName, fiducialSetId, subjectsId, yearClassId, lessonNumList, startLessonNum, endLessonNum, export, examNum, dataType);
            } else if (type == 3) {
                iRadeDataService.getRateByChargeTeacherOwnList(iPage, yearPart, quarterNum, schoolId, teacherName, fiducialSetId, subjectsId, yearClassId, lessonNumList, startLessonNum, endLessonNum, export, departmentId, examNum, dataType);
            }
        } else if (dataModule == 2) {
            if (type == 2) {
                iRadeDataService.getRateByYearClassTeacherList(iPage, yearPart, quarterNum, schoolId, teacherName, fiducialSetId, subjectsId, yearClassId, lessonNumList, startLessonNum, endLessonNum, export, examNum, dataType);
            } else if (type == 3) {
                iRadeDataService.getRateByChargeTeacherList(iPage, yearPart, quarterNum, schoolId, teacherName, fiducialSetId, subjectsId, yearClassId, lessonNumList, startLessonNum, endLessonNum, export, departmentId, examNum, dataType);
            }
        }

        if (export == 1) {

            Integer freezingCount = 1;
            if (type == 1) {
                freezingCount = 4;
            } else if (type == 2) {
                freezingCount = 5;
            } else if (type == 3) {
                freezingCount = 6;
            }
            freezingCount = freezingCount + endLessonNum - startLessonNum + 1;
            String freezingColumns = "A1:" + ExcelUtils.convertNumbersToExcelColumnNumbers(freezingCount) + "1";
            CellRangeAddress cellRangeAddress = CellRangeAddress.valueOf(freezingColumns);

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
            sheet.createFreezePane(0, 1);
            sheet.setAutoFilter(cellRangeAddress);

            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(30);

            CellStyle headerCellStyle = ExcelUtils.headCommonCellStyle(workbook);

            CellStyle cellStyle = ExcelUtils.bodyCommonCellStyle(workbook, null);

            CellStyle cellStyle1 = ExcelUtils.bodyCommonCellStyle(workbook, IndexedColors.BRIGHT_GREEN);
            cellStyle1.setDataFormat(workbook.createDataFormat().getFormat("0.00%"));

            CellStyle cellStyle2 = ExcelUtils.bodyCommonCellStyle(workbook, IndexedColors.YELLOW);
            cellStyle2.setDataFormat(workbook.createDataFormat().getFormat("0.00%"));

            CellStyle cellStyle3 = ExcelUtils.bodyCommonCellStyle(workbook, IndexedColors.RED);
            cellStyle3.setDataFormat(workbook.createDataFormat().getFormat("0.00%"));

            CellStyle cellStyle4 = ExcelUtils.bodyCommonCellStyle(workbook, null);
            cellStyle4.setDataFormat(workbook.createDataFormat().getFormat("0.00%"));

            // 非成绩数据
            List<String> headList = new ArrayList<>();
            headList.add("大校区");
            headList.add("项目");
            headList.add("科目");

            if (dataModule == 1) {
                if (type == 1) {
                    headList.add("年级");
                    headList.add("教师");
                } else if (type == 2) {
                    headList.add("年级负责人");
                } else if (type == 3) {
                    headList.add("部门");
                    headList.add("主管");
                }
            } else if (dataModule == 2) {
                if (type == 2) {
                    if (dataType.equals(1)) {
                        headList.add("年级");
                    }
                    headList.add("年级负责人");
                } else if (type == 3) {
                    headList.add("部门");
                    headList.add("主管");
                }
            }
            if (dataType.equals(2)) {
                if (fiducialSetId.equals("14")) {
                    startYearClassId = 3;
                }
                for (Integer i = startYearClassId; i <= endYearClassId; i++) {
                    headList.add(CommonUtil.getYearClassNameForId(i));
                }
            } else {
                for (Integer i = startLessonNum; i <= endLessonNum; i++) {
                    headList.add("第" + i + "次课");
                }
            }

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
                sheet.setColumnWidth(i, 25 * 256);
            }

            int rowIndex = 1;

            for (RadeDataRs radeDataRs : iPage.getRecords()) {

                Row row = sheet.createRow(rowIndex);
                row.setHeightInPoints(20);

                Cell cell0 = row.createCell(0);
                cell0.setCellValue(radeDataRs.getSchoolName());
                sheet.setColumnWidth(0, 25 * 256);
                cell0.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(radeDataRs.getProjectsName());
                sheet.setColumnWidth(1, 25 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                if (StringUtils.isBlank(radeDataRs.getSubjectsName())) {
                    radeDataRs.setSubjectsName("全部");
                }
                cell2.setCellValue(radeDataRs.getSubjectsName());
                sheet.setColumnWidth(2, 15 * 256);
                cell2.setCellStyle(cellStyle);

                int columnIndex = 3;

                if (((type == 2 && dataModule == 2) || (type == 1 && dataModule == 1)) && dataType.equals(1)) {
                    Cell cell3 = row.createCell(columnIndex);
                    if (radeDataRs.getYearClassId() != null) {
                        cell3.setCellValue(CommonUtil.getYearClassNameForId(Integer.valueOf(radeDataRs.getYearClassId())));
                    } else {
                        cell3.setCellValue("全部");
                    }
                    sheet.setColumnWidth(columnIndex, 15 * 256);
                    cell3.setCellStyle(cellStyle);
                    columnIndex++;
                } else if (type == 3) {
                    Cell cell3 = row.createCell(columnIndex);
                    cell3.setCellValue(radeDataRs.getDepartmentName());
                    sheet.setColumnWidth(columnIndex, 15 * 256);
                    cell3.setCellStyle(cellStyle);
                    columnIndex++;
                }

                Cell cell4 = row.createCell(columnIndex);
                cell4.setCellValue(radeDataRs.getTeacherName());
                sheet.setColumnWidth(columnIndex, 15 * 256);
                cell4.setCellStyle(cellStyle);

                if (StringUtils.isNotBlank(radeDataRs.getRadeNum())) {
                    List<String> lessonNums = new ArrayList<>();
                    if (dataType.equals(2)) {
                        lessonNums = Arrays.asList(radeDataRs.getYearClassId().split(","));
                    } else {
                        lessonNums = Arrays.asList(radeDataRs.getLessonNum().split(","));
                    }

                    List<String> radeNums = Arrays.asList(radeDataRs.getRadeNum().split(","));
                    List<String> rankTypes = Arrays.asList(radeDataRs.getRankType().split(","));

                    for (int j = 0; j < lessonNums.size(); j++) {
                        int lessonNum = Integer.parseInt(lessonNums.get(j));
                        int rankType = Integer.parseInt(rankTypes.get(j));
                        String radeNum = radeNums.get(j);

                        if (dataType.equals(2)) {
                            if (lessonNum < startYearClassId || lessonNum > endYearClassId) {
                                continue;
                            }
                        }

                        int colIndex = 0;

                        if (dataType.equals(2)) {
                            colIndex = columnIndex + 1 + (lessonNum - startYearClassId);
                        } else {
                            colIndex = columnIndex + 1 + (lessonNum - startLessonNum);
                        }

                        Cell cell = row.createCell(colIndex);
                        cell.setCellValue(Double.parseDouble(radeNum) / 100);
                        sheet.setColumnWidth(colIndex, 15 * 256);
                        if (rankType == 1) {
                            // 第1名，绿色
                            cell.setCellStyle(cellStyle1);
                        } else if (rankType == 2) {
                            // 在基准值之上，黄色
                            cell.setCellStyle(cellStyle2);
                        } else if (rankType == 3) {
                            // 在基准值之下，红色
                            cell.setCellStyle(cellStyle3);
                        } else if (rankType == 4) {
                            // 最后一名，红色
                            cell.setCellStyle(cellStyle3);
                        }
                    }

                    if (dataType.equals(2)) {
                        for (int i = startYearClassId; i <= endLessonNum; i++) {
                            int colIndex = columnIndex + 1 + (i - startYearClassId);
                            boolean hasData = false;
                            for (int j = 0; j < lessonNums.size(); j++) {
                                int lessonNum = Integer.parseInt(lessonNums.get(j));
                                if (lessonNum == i) {
                                    hasData = true;
                                    break;
                                }
                            }
                            if (!hasData) {
                                Cell cell = row.createCell(colIndex);
                                cell.setCellValue("无");
                                cell.setCellStyle(cellStyle);
                            }
                        }
                    } else {
                        for (int i = startLessonNum; i <= endLessonNum; i++) {
                            int colIndex = columnIndex + 1 + (i - startLessonNum);
                            boolean hasData = false;
                            for (int j = 0; j < lessonNums.size(); j++) {
                                int lessonNum = Integer.parseInt(lessonNums.get(j));
                                if (lessonNum == i) {
                                    hasData = true;
                                    break;
                                }
                            }
                            if (!hasData) {
                                Cell cell = row.createCell(colIndex);
                                cell.setCellValue("无");
                                cell.setCellStyle(cellStyle);
                            }
                        }
                    }
                }

                rowIndex++;
            }


            String fileName = "业绩数据" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置为excel格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 更新数据汇总
     *
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @PostMapping("/updateRadeDataBatch")
    public Result updateRadeDataBatch(@RequestParam(value = "yearPart", required = false) Integer yearPart,
                                      @RequestParam(value = "quarterNum", required = false) Integer quarterNum) {

        IntegralStatisticsRs statisticsRs = new IntegralStatisticsRs();
        statisticsRs.setId(0L);
        statisticsRs.setYearPart(yearPart);
        statisticsRs.setQuarterNum(quarterNum);

        iMqPushService.updateRadeDataBatch(statisticsRs);

        return new Result(Code.OK, "", "更新中");
    }

}
